package repository

import (
	"RocFamilySystem/tools/container"
	"fmt"
	"gorm.io/gorm"
	"log"
	"reflect"
	"runtime"
)

var registerContainer = make(map[string]any)

func InitRepository() {
	db, ok := container.GetBeanContainer("gorm.DB")
	if !ok {
		log.Panicln("数据库未初始化！")
	}

	for _, val := range registerContainer {
		v := reflect.ValueOf(val)
		method := v.MethodByName("SetDB")
		method.Call([]reflect.Value{reflect.ValueOf(db)})
		container.PushContainer(val)
	}
}

func handleRepositoryErr(err error, msg string) {
	_, file, line, _ := runtime.Caller(1)
	if err != nil {
		fmt.Printf("%s:%d\n", file, line)
		log.Println("SQL执行错误：", err.Error())
		log.Panicln("系统错误：", msg)
	}
}

// 回滚事务
func handleTransactional(db *gorm.DB) {
	err := recover()
	if err != nil {
		db.Rollback()
		panic(err)
		return
	}

	db.Commit()
}
